﻿
using AutoMapper;
using IoTAdapter;
using IoTAdapter.BaseCore;
using IoTAdapter.BaseCore.Enums;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using WCS.Entities;
using WCS.ViewModels;

namespace WCS.Services
{
    public class ReportHub : Hub
    {
        private readonly ILogger<ReportHub> logger;
        private static NetworkDeviceBase readWrite;
        private readonly IMapper mapper;
        public ReportHub(
            ILogger<ReportHub> logger,
            IMapper mapper)
        {
            this.logger = logger;
            this.mapper = mapper;

        }
        public override Task OnConnectedAsync()
        {
            var cid = Context.ConnectionId;

            //根据id获取指定客户端
            var client = Clients.Client(cid);
            logger.LogInformation("The signalR client({0}) has connected!", cid);
            return base.OnConnectedAsync();
        }
        public override Task OnDisconnectedAsync(Exception ex)
        {

            var cid = Context.ConnectionId;

            //根据id获取指定客户端
            var client = Clients.Client(cid);
            logger.LogError("The signalR client({0}) has disconnected!", cid);

            return base.OnDisconnectedAsync(ex ?? new Exception());
        }

        #region DeviceMethod
        public bool ConnectedDevice(string ip, int port, string type, byte station, bool isStartWithOne)
        {
            var deviceType = (EthernetDeviceVersion)Enum.Parse(typeof(EthernetDeviceVersion), type);
            readWrite = (NetworkDeviceBase)IoTClientFactory.CreateClientEthernetDevice(deviceType, ip, port, station, 15000, isStartWithOne);
            readWrite.Connect();
            logger.LogInformation("query Device Info");
            SetResult($"{ip} 连接成功！");
            return readWrite.IsConnected;

        }

        public void CloseDevice(string ip)
        {
            readWrite?.Close();
            SetResult($"{ip} 断开连接！");
        }

        public void Read(string address, int type, bool isShowText)
        {
            var dataType = (DataTypeEnum)(type + 1);
            string message, text;
            if (readWrite.IsConnected)
            {
                switch (dataType)
                {
                    case DataTypeEnum.None:

                        break;
                    case DataTypeEnum.Bool:
                        var result = readWrite.ReadBool(address);
                        message = result.IsSucceed ? $"结果为:{result.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result.Requst}\n 响应报文:{result.Response}" : "";
                        SetResult(message + text);

                        break;
                    case DataTypeEnum.Byte:
                        var result1 = readWrite.ReadByte(address);
                        message = result1.IsSucceed ? $"结果为:{result1.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result1.Requst}\n 响应报文:{result1.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.Int16:
                        var result2 = readWrite.ReadInt16(address);
                        message = result2.IsSucceed ? $"结果为:{result2.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result2.Requst}\n 响应报文:{result2.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.UInt16:
                        var result3 = readWrite.ReadUInt16(address);
                        message = result3.IsSucceed ? $"结果为:{result3.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result3.Requst}\n 响应报文:{result3.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.Int32:
                        var result4 = readWrite.ReadInt32(address);
                        message = result4.IsSucceed ? $"结果为:{result4.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result4.Requst}\n 响应报文:{result4.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.UInt32:
                        var result5 = readWrite.ReadUInt32(address);
                        message = result5.IsSucceed ? $"结果为:{result5.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result5.Requst}\n 响应报文:{result5.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.Int64:
                        var result6 = readWrite.ReadInt64(address);
                        message = result6.IsSucceed ? $"结果为:{result6.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result6.Requst}\n 响应报文:{result6.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.UInt64:
                        var result7 = readWrite.ReadUInt64(address);
                        message = result7.IsSucceed ? $"结果为:{result7.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result7.Requst}\n 响应报文:{result7.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.Single:
                        var result8 = readWrite.ReadFloat(address);
                        message = result8.IsSucceed ? $"结果为:{result8.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result8.Requst}\n 响应报文:{result8.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.Double:
                        var result9 = readWrite.ReadDouble(address);
                        message = result9.IsSucceed ? $"结果为:{result9.Value}" : "读取失败";
                        text = isShowText ? $"\n请求报文:{result9.Requst}\n 响应报文:{result9.Response}" : "";
                        SetResult(message + text);
                        break;
                    case DataTypeEnum.String:
                        break;
                    default:
                        break;
                }
            }
            else
            {
                SetResult($"读取之前先连接设备");

            }
        }

        public void Write(string address, string value, int type, bool isShowText)
        {
            var dataType = (DataTypeEnum)(type + 1);
            string message, text;
            Result result = new Result();
            if (readWrite.IsConnected)
            {
                switch (dataType)
                {
                    case DataTypeEnum.None:

                        break;
                    case DataTypeEnum.Bool:
                        result = readWrite.Write(address, bool.Parse(value));
                        break;
                    case DataTypeEnum.Byte:
                        result = readWrite.Write(address, byte.Parse(value));
                        break;
                    case DataTypeEnum.Int16:
                        result = readWrite.Write(address, short.Parse(value));
                        break;
                    case DataTypeEnum.UInt16:
                        result = readWrite.Write(address, ushort.Parse(value));
                        break;
                    case DataTypeEnum.Int32:
                        result = readWrite.Write(address, int.Parse(value));
                        break;
                    case DataTypeEnum.UInt32:
                        result = readWrite.Write(address, uint.Parse(value));
                        break;
                    case DataTypeEnum.Int64:
                        result = readWrite.Write(address, long.Parse(value));
                        break;
                    case DataTypeEnum.UInt64:
                        result = readWrite.Write(address, ulong.Parse(value));
                        break;
                    case DataTypeEnum.Single:
                        result = readWrite.Write(address, float.Parse(value));
                        break;
                    case DataTypeEnum.Double:
                        result = readWrite.Write(address, double.Parse(value));
                        break;
                    case DataTypeEnum.String:
                        break;
                    default:
                        break;
                }
                message = result.IsSucceed ? $"写入成功" : "写入失败";
                text = isShowText ? $"\n请求报文:{result.Requst}\n 响应报文:{result.Response}" : "";
                SetResult(message + text);
            }
            else
            {
                SetResult($"读取之前先连接设备");

            }
        }
        private void SetResult(string message)
        {

            var reponse = $"{DateTime.Now.ToString("HH:mm:ss")}:{message}\n";
            Clients.All.SendAsync("OnDeviceInfo", new { isConnected = readWrite.IsConnected, result = reponse });
        }
        #endregion
    }
}
